<?php

/**
 *	dropbox module
 *	this module interacts with any dropbox account defined in settings
 *	interaction with dropbox is based on the dropbox php class on http://code.google.com/p/dropbox-php/
 *	
 *	all internal and output functions are declared in the class itself	
 *	@todo		filters  for user info, file & directory info, meta info from files, thumbnails form images
 *	@todo		maybe slideshow from folders
 *
 *	@package 	engine modules
 *	@author		2010 - pieter van peteghem <pieter@onedotonly.be> 
 *	@date		23 nov 2010
 *	@version	1.1 beta
 */


require_once ROOT . 'engine/ext/dropbox/dropbox.php';

class SocialDropbox extends MOD {

	
	/**
	 *	define output by json string in db (moddump)
	 *	@param		string - action
	 *	@return		string - html code
	 */
	
	public function output () {
		
		// dropbox api connect
		//$this->dropbox 		= $this->dropbox_connect();
		
		// define action - get result
		if( $this->action )
			$result = $this->{ "filter_" . $this->action }();
	
		// show result
		return $this->parse( $result );
		
	}
	
	
	private function filter_browse() {
		global $DB;
		
		$dp			= json_decode( engine_get( 'dropbox' ));
		$dp_key		= $dp->key;
		$dp_secret	= $dp->secret;
				
		$Dropbox	= new Dropbox( $dp_key, $dp_secret );
		if( !$dp->token ) {
			$response = $Dropbox->token( $this->vars->username, $this->vars->password );
			$settings	= array(
				'key' 			=> $dp_key,
				'secret'		=> $dp_secret,
				'token'			=> $response[ 'token' ],
				'token_secret'	=> $response[ 'secret' ]
			);
			$DB->query( "UPDATE `settings` set `value` = '" . json_encode( $settings ) . "' where `key` = 'dropbox' LIMIT 1" );

			$dp_token		= $settings[ 'token' ];
			$dp_tokensecret	= $settings[ 'token_secret' ];
		} else {
			$dp_token		= $dp->token;
			$dp_tokensecret	= $dp->token_secret;
		}
			
				
		// key		n51wp2leo50m0wt
		// secret	670qeffbmj3h7tk
		
		// token	awr8prsgbvwzxhn
		// secret 	i4qxkub2p4ykp1x
			
		$Dropbox->setOAuthToken( $dp_token ); 
		$Dropbox->setOAuthTokenSecret( $dp_tokensecret ); 
		
		$user	= $Dropbox->accountInfo();
		
		$files		= $Dropbox->metadata( 'Public/' );
		if( $files ) {
			$res .= '<ul>';
			foreach( $files[ 'contents' ] as $file ) {
				$path	= array_pop( explode( '/', $file[ 'path' ] ));
				$res .= '<li class="dropbox">';
				$res .= '<a title="' . $path . '" href="http://dl.dropbox.com/u/' . $user[ 'uid' ] . '/' . rawurlencode( $path ) . '">' . $path . '</a>';
				$res .= '</li>';
			}
			$res .= '</ul>';
		}
		
		return $res;
	}
				
}
